package com.sunxueqi.framework.manager;

import java.sql.Timestamp;
import java.util.TimerTask;

import com.sunxueqi.common.constant.StatusConstants;
import com.sunxueqi.common.utils.AddressUtils;
import com.sunxueqi.common.utils.IpUtils;
import com.sunxueqi.common.utils.KeyGenerate;
import com.sunxueqi.common.utils.ServletUtils;
import com.sunxueqi.common.utils.SpringUtils;
import com.sunxueqi.project.log.service.ILoginLogService;
import com.sunxueqi.project.log.service.IOperationLogService;
import com.sunxueqi.project.log.service.IVisitLogService;
import com.sunxueqi.project.log.vo.LoginLog;
import com.sunxueqi.project.log.vo.OperationLog;
import com.sunxueqi.project.log.vo.VisitLog;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class AsyncFactory {

	Log log = LogFactory.get();
	
	/**
	 * 记录登录日志
	 * @param username
	 * @param state
	 * @param message
	 * @return
	 */
	public static TimerTask recordLoginLog(String username, String state, String message) {
		
		UserAgent usetAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
		String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
		String address = AddressUtils.getCityInfoByIp(ip);
				
		return new TimerTask() {
			@Override
			public void run() {
				LoginLog loginLog = new LoginLog();
				loginLog.setId(KeyGenerate.getKeyId());
				loginLog.setUsername(username);
				loginLog.setIp(ip);
				loginLog.setLocation(address);
				loginLog.setBrowser(usetAgent.getBrowser().toString());
				loginLog.setVersion(usetAgent.getVersion());
				loginLog.setOs(usetAgent.getOs().toString());
				loginLog.setPlatform(usetAgent.getPlatform().toString());
				loginLog.setStatus(state);
				loginLog.setMessage(message);
				loginLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
				loginLog.setDeleteStatus(StatusConstants.NORMAL);
				
				SpringUtils.getBean(ILoginLogService.class).addLog(loginLog);
			}
		};
	}
	
	/**
	 * 记录操作日志
	 * @param operationLog
	 * @return
	 */
	public static TimerTask recordOperateLog(final OperationLog operationLog) {
		return new TimerTask() {
			@Override
			public void run() {
				SpringUtils.getBean(IOperationLogService.class).insertOperationLog(operationLog);
			}
		};
	}
	
	/**
	 * 记录访问日志
	 * @param visitLog
	 * @return
	 */
	public static TimerTask recordVisitLog(final VisitLog visitLog) {
		return new TimerTask() {
			@Override
			public void run() {
				SpringUtils.getBean(IVisitLogService.class).insertVisitLog(visitLog);
			}
		};
	}
}
